package org.csu.mypetstore.service;

import org.csu.mypetstore.domain.*;
import org.csu.mypetstore.persistence.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sound.sampled.Line;
import java.util.List;

@Service
public class AdminService {
    @Autowired
    SequenceMapper sequenceMapper;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    LineItemMapper lineItemMapper;

    @Autowired
    ItemMapper itemMapper;

    @Autowired
    AccountMapper accountMapper;

    @Autowired
    ProductMapper productMapper;

    //更新序列并且得到新的orderId
    public int updateSequenceGetOrderId(Sequence sequence){
        sequence = sequenceMapper.getSequence(sequence);
        int orderId = (1000 - sequence.getNextId());
        sequence.setNextId(sequence.getNextId()-1);
        sequenceMapper.updateSequence(sequence);

        return orderId;
    }

    //插入order
    public void insertOrder(Order order){
        orderMapper.insertOrder(order);
        orderMapper.insertOrderStatus(order);
    }

    //插入购买商品信息
    public void insertLineItem(LineItem lineItem){
        lineItemMapper.insertLineItem(lineItem);
    }

    //更新库存
    public void updateInventory(LineItem lineItem){
        int newQuantity = itemMapper.getInventoryQuantity(lineItem.getItemId()) - lineItem.getQuantity();

        itemMapper.updateInventoryQuantity(lineItem.getItemId(),newQuantity);
    }

    //根据用户名得到历史订单
    public List<Order> getOrdersByUsername(String username){
        return orderMapper.getOrdersByUsername(username);
    }

    //根据订单号得到订单
    public Order getOrderByOrderId(int orderInt){
        return orderMapper.getOrder(orderInt);
    }

    //根据订单号得到订单商品序列
    public List<LineItem> getLineItemsByOrderId(int orderInt){
        return lineItemMapper.getLineItemsByOrderId(orderInt);
    }

    //更新订单状态
    public void upDateOrderStatus(String orderId){
        orderMapper.updateOrder(orderId);
    }

    //得到目前所有的未处理订单
    public List<Order> getUnhandledOrders(){
        return orderMapper.getUnhandledOrders();
    }

    //禁用用户的账户
    public void banAccount(String username){
        accountMapper.updateAccountBan(username);
    }

    //解禁用户的账户
    public void unbanAccount(String username){
        accountMapper.updateAccountUnban(username);
    }

    //删除Item
    public void  admindelete(String itemId){
        itemMapper.admindelete(itemId);
    }

    //增加Item
    public void addItem(Item item){
        itemMapper.insertItem(item);
        itemMapper.insertInventory(item.getItemId(),item.getQuantity());
    }

    //增加Product
    public void addProduct(Product product){
        productMapper.insertProduct(product);
    }
}
